#coding=utf8

import Queue
import threading

import gevent
import gevent.socket

import initpath
import proto2packet
from transport import TransportHandler,show_msg
from network import * 

addr = '127.0.0.1'
port = 2345
sock = gevent.socket.create_connection((addr,port))
lets = None

def send(msg):
	proto2packet.send(sock,msg)

def closesock(_):
	print lets
	for let in lets:
		let.kill()

class ClientHandler(TransportHandler):
	def __init__(self,sock):
		super(ClientHandler,self).__init__(sock)
		self._sock = sock
		self._input_queue = Queue.Queue()
		self._g = gevent.spawn(self.listen_input)
	
	def _on_close_transport(self):
		super(ClientHandler,self)._on_close_transport()
		self._g.kill()
		
	def listen_input(self):
		while True:
			gevent.sleep(0.1)
			try:
				msg = self._input_queue.get_nowait()
			except Queue.Empty:
				continue
			if msg == '0':
				self._sock.close()
				break
			self._send(msg)

	def init_proto_handler(self):
		self._proto2handler = {
				protocode.MOVERESP:self.on_moveresp,				
				}
	@show_msg
	def on_moveresp(self,msg):
		print msg.text

	def send(self,msg):
		self._input_queue.put(msg)

	def loop(self):
		gevent.joinall(self._transport._lets)
	
	def stop(self):
		print 'client handler stop'
		self._input_queue.put('0')	

def run_input_loop(handler):
	while True:
		try:
			data = raw_input('>>')
		except Exception,e:
			print str(e)
			break
		if not data:
			continue
		if data == 'quit':
			handler.stop()
			break
		msg = None
		if data.isdigit():
			msg = proto.Light()
			msg.intensity = int(data)
		else:
			msg = proto.MoveReq()
			msg.text = data
		handler.send(msg)
		print 'send msg'
	print 'input break'

def main():
	handler = ClientHandler(sock)
	t = threading.Thread(target=run_input_loop,args=(handler,))
	t.start()
	handler.loop()

if __name__ == '__main__':
	main()
